package com.quectel.emp.controller.household;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.constant.core.household.HouseholdConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.dto.HouseholdFollowLogDto;
import com.quectel.core.module.household.service.HouseholdFollowLogService;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.emp.controller.BaseController;
import com.quectel.emp.util.SessionHolder;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/03/10 11:46
 */
@RestController
@RequestMapping("householdFollowLog")
@Tag(name = "HouseholdFollowLogController", description = "重点住户跟进相关api")
public class HouseholdFollowLogController extends BaseController {

    @DubboReference
    private HouseholdService householdService;
    @DubboReference
    private HouseholdFollowLogService householdFollowLogService;


    /**
     * 根据参数分页查询重点住户列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @Operation(summary = "根据参数分页查询重点住户列表")
    public Response<Page<HouseholdFollowLogDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "住户ID") @RequestParam Long householdId,
            @Parameter(description = "开始日期,日期格式yyyy-MM-dd") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束日期,日期格式yyyy-MM-dd") @RequestParam(required = false) String endTime

    ) {
        HouseholdDto householdDto = householdService.selectCacheById(householdId);
        if (householdDto == null) {
            return Response.error("住户不存在");
        }

        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        request.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getTenantId), SessionHolder.getEmp().getTenantId());
        request.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getVillageId), SessionHolder.getEmp().getVillageId());
        request.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getHouseholdId), householdId);

        //时间筛选
        if (StringUtils.isNotBlank(startTime)) {
            Date startDate = DateUtils.parse(startTime, DateUtils.FormatType.SIMPLE);
            String startDateStr = DateUtils.format(DateUtil.beginOfDay(startDate), DateUtils.FormatType.COMMON);
            request.put(HouseholdConstants.ASK_TIME_SLOT_KEY_PAIR.getLeft(), startDateStr);
        }

        if (StringUtils.isNotBlank(endTime)) {
            Date endDate = DateUtils.parse(endTime, DateUtils.FormatType.SIMPLE);
            String endDateStr = DateUtils.format(DateUtil.endOfDay(endDate), DateUtils.FormatType.COMMON);
            request.put(HouseholdConstants.ASK_TIME_SLOT_KEY_PAIR.getRight(), endDateStr);
        }

        //按照跟进时间倒序
        request.put(SystemConstants.SORT_ORDER_BY_KEY, HouseholdConstants.ASK_TIME);
        request.put(SystemConstants.SORT_ORDER_RULE_KEY, SystemConstants.SORT_ORDER_RULE_DESC);

        int total = householdFollowLogService.queryTotal(request.getParams());

        List<HouseholdFollowLogDto> list = null;
        if (total > 0) {
            list = householdFollowLogService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<HouseholdFollowLogDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<HouseholdFollowLogDto>>ok().wrap(page);
    }

    private List<String> getContradictionNameList(HouseholdFollowLogDto logDto) {
        List<String> nameList = new ArrayList<>();

        if (StringUtils.isNotEmpty(logDto.getContradictionJsonArr())) {
            List<JsonNode> jsonNodes = JacksonUtils.parseArray(logDto.getContradictionJsonArr());
            for (JsonNode jsonNode : jsonNodes) {
                nameList.add(SysCodeUtils.easyToGetName(SysCodeKeyConstants.SOCIAL_CONTRADICTIONS, jsonNode.textValue()));
            }
        }
        return nameList;

    }

    /**
     * 根据id查询住户跟进单条记录，编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @Operation(summary = "根据id查询住户跟进单条记录，编辑查询反显")
    public Response<HouseholdFollowLogDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getTenantId), SessionHolder.getEmp().getTenantId());
        params.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getVillageId), SessionHolder.getEmp().getVillageId());
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (householdFollowLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        HouseholdFollowLogDto householdFollowLogDto = householdFollowLogService.selectById(id);
        householdFollowLogDto.setContradictionNameList(getContradictionNameList(householdFollowLogDto));

        return Response.<HouseholdFollowLogDto>ok().wrap(householdFollowLogDto);
    }

    /**
     * 根据id查询住户跟进单条记录
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @Operation(summary = "根据id查询住户跟进单条记录")
    public Response<HouseholdFollowLogDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getTenantId), SessionHolder.getEmp().getTenantId());
        params.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getVillageId), SessionHolder.getEmp().getVillageId());
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (householdFollowLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        HouseholdFollowLogDto householdFollowLogDto = householdFollowLogService.selectById(id);
        householdFollowLogDto.setContradictionNameList(getContradictionNameList(householdFollowLogDto));

        return Response.<HouseholdFollowLogDto>ok().wrap(householdFollowLogDto);
    }

    /**
     * 保存住户跟进单条记录
     *
     * @param householdFollowLogDto
     * @return
     */
    @PostMapping("save")
    @Operation(summary = "保存住户跟进单条记录")
    public Response<Object> save(@RequestBody @Validated HouseholdFollowLogDto householdFollowLogDto) {

        HouseholdDto householdDto = householdService.selectCacheById(householdFollowLogDto.getHouseholdId());
        if (householdDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        householdFollowLogDto.setTenantId(householdDto.getTenantId());
        householdFollowLogDto.setVillageId(householdDto.getVillageId());
        householdFollowLogDto.setHouseholdId(householdDto.getId());

        //填充责任人
        householdFollowLogDto.setFollowerName(SessionHolder.getEmp().getName());
        householdFollowLogDto.setFollowerMobile(SessionHolder.getEmp().getMobile());

        //来源
        householdFollowLogDto.setSourceType(HouseholdConstants.FollowSourceType.EMP.getType());

        householdFollowLogService.save(householdFollowLogDto);

        return Response.ok();
    }


    /**
     * 修改住户跟进单条记录
     *
     * @param householdFollowLogDto
     * @return
     */
    @PostMapping("update")
    @Operation(summary = "修改住户跟进单条记录")
    public Response<Object> update(@RequestBody @Validated HouseholdFollowLogDto householdFollowLogDto) {

        HouseholdDto householdDto = householdService.selectCacheById(householdFollowLogDto.getHouseholdId());
        if (householdDto == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        Map<String, Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getTenantId), SessionHolder.getEmp().getTenantId());
        params.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getVillageId), SessionHolder.getEmp().getVillageId());
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(householdFollowLogDto.getId()));
        if (householdFollowLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        householdFollowLogDto.setTenantId(householdDto.getTenantId());
        householdFollowLogDto.setVillageId(householdDto.getVillageId());
        householdFollowLogService.updateById(householdFollowLogDto);

        return Response.ok();
    }

    /**
     * 批量删除住户跟进单条记录
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @Operation(summary = "批量删除住户跟进单条记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getTenantId), SessionHolder.getEmp().getTenantId());
        params.put(LambdaUtil.getFieldName(HouseholdFollowLogDto::getVillageId), SessionHolder.getEmp().getVillageId());

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (householdFollowLogService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        householdFollowLogService.deleteBatch(ids);

        return Response.ok();
    }
}
